<script lang="tsx">
import { defineComponent, ref, watch, h, compile, computed } from 'vue';
import {
  useRouter,
  useRoute,
  RouteRecordRaw,
  RouteRecordNormalized,
} from 'vue-router';
import { useAppStore } from '@/store';
import { useMenuStore } from '@/store';

const rws = ['dashboard']
const sws = ['workplace']

export default defineComponent({
  emit: ['collapse'],
  setup() {
    const appStore = useAppStore();
    const router = useRouter();
    const route = useRoute();
    const collapsed = ref(false);
    const appRoute = computed(() => {
      return router
        .getRoutes()
        .find((el) => el.name === 'root') as RouteRecordNormalized;
    });
    const menuTree = computed(() => {
      const copyRouter = JSON.parse(JSON.stringify(appRoute.value.children));
      function travel(_routes: RouteRecordRaw[], layer: number) {
        if (!_routes) return null;
        const collector: any = _routes.map((element) => {

          // leaf node
          if (!element.children) {
            return element;
          }

          // Associated child node
          const subItem = travel(element.children, layer);
          if (subItem.length) {
            element.children = subItem;
            return element;
          }
          // the else logic
          if (layer > 1) {
            element.children = subItem;
            return element;
          }
          return null;
        });
        return collector.filter(Boolean);
      }
      return travel(copyRouter, 0);
    });

    // In this case only two levels of menus are available
    // You can expand as needed

    const selectedKey = ref<string[]>([]);
    const goto = (item: RouteRecordRaw) => {
      router.push({ name: item.name });
    };
    const openLabel = (item) => {
      console.log("打开外链: ", item)
      window.open(item.links, '_blank')
    }
    watch(
      route,
      (newVal) => {
        if (newVal.meta.requiresAuth) {
          const key = newVal.matched[2]?.name as string;
          selectedKey.value = [key];
        }
      },
      {
        immediate: true,
      }
    );
    watch(
      () => appStore.menuCollapse,
      (newVal) => {
        collapsed.value = newVal;
      },
      {
        immediate: true,
      }
    );
    const setCollapse = (val: boolean) => {
      appStore.updateSettings({ menuCollapse: val });
    };

    const renderSubMenu = () => {
      const menuStore = useMenuStore();
      function travel(_route: RouteRecordRaw[], _menus = [], nodes = []) {
        if (_route) {
          _route.forEach((ele, idx) => {

            if(ele.type !== 1) return;
            const _menu = _menus.find(item => item['path'] === ele['front_route']);

            const icon = ele?.icon ? `<${ele?.icon}/>` : `<${_menu?.meta?.icon}/>`;

            let r = null; 

            if(ele.mode === 3){
              r = (
                <a-menu-item key={ele.name} onClick={() => openLabel(ele)} v-slots={{
                  icon: () => h(compile(`${icon}`))
                }}>
                {ele.name} <span style={{ position: 'absolute', right: 0, top: '4px' }}><icon-launch /></span>
                </a-menu-item>
              );
            }else {
              r = (
                <a-sub-menu
                  key={ele?.name || _menu?.meta?.locale}
                  v-slots={{
                    title: () => h(compile(`${icon}${ele?.name || _menu?.meta?.locale}`))
                  }}
                >
                {
                  ele?.children?.map((el) => {

                    const subMenu = _menu?.children?.find(item => item['path'] === el['front_route']) 
                    const itemIcon = el?.icon ? `<${el?.icon}/>` : ``;

                    return (
                      <a-menu-item key={subMenu?.name} onClick={() => goto(subMenu)} v-slots={{
                        icon: () => h(compile(`${itemIcon}`))
                      }}>
                        {el.name}
                        {travel(el.children ?? [], subMenu?.children ?? [])}
                      </a-menu-item>
                    );
                  })
                }
                </a-sub-menu>
              );
            }

            nodes.push(r as never);
          });
        }
        return nodes;
      }
      return travel(menuStore.menus, menuTree.value);
    };
    return () => (
      <a-menu
        v-model:collapsed={collapsed.value}
        selected-keys={selectedKey.value}
        accordion
        auto-open-selected
        show-collapse-button
        level-indent={34}
        onCollapse={setCollapse}
      >
        {renderSubMenu()}
      </a-menu>
    );
  },
});
</script>

<style lang="less" scoped>
.arco-menu {
  height: 100%;
}

:deep(.arco-menu-inner) {
  .arco-menu-inline-header {
    display: flex;
    align-items: center;
    user-select: none;
  }

  .arco-menu-item {
    user-select: none;
  }

  .arco-icon {
    &:not(.arco-icon-down) {
      font-size: 18px;
    }
  }

  .arco-menu-pop-header {
    &:not(.arco-menu-has-icon) {
      height: 40px;
      white-space: normal;
      text-overflow: clip;
    }
  }
}
</style>
